package webTest.sessionCookie.LastView;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by IFT8 on 2015/1/26.
 *
 */
public class BookInfo extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String id = request.getParameter("id");
        Book book = BookDAO.getBook(id);
        if (book == null) {
            response.getWriter().print("ID错误，找不到该书……");
            return;
        }
        response.getWriter().print("<h1>" + book.getName() + "</h1>");
        response.getWriter().print("<a href='" + request.getContextPath() + "Index'>[返回]</a>");
        //&emsp;相当于/t
        response.getWriter().print("<h3>作者：&emsp;" + book.getAuthor() + "</h3>");
        response.getWriter().print("<h3>出版社：&emsp;" + book.getPublisher() + "</h3>");
        response.getWriter().print("<h3>售价：&emsp;" + book.getPrice() + "</h3>");
        response.getWriter().print("<h3>简介：&emsp;" + book.getDescription() + "</h3>");
        /*记录本次看的书*/
        Cookie cookie = new Cookie("lastView", "");
        cookie.setMaxAge(60 * 60 * 24);//以秒为单位，没有设置MaxAge就默认为会话级Cookie,0为删除
        Cookie[] cookies = request.getCookies();
        String lastView = null;
        StringBuilder newLastView = new StringBuilder();
        if (cookies != null) {
            //获取以前看到书
            for (Cookie cookie1 : cookies) {
                if ("lastView".equals(cookie1.getName())) {
                    lastView = cookie1.getValue();
                    break;
                }
            }
        }
        if (lastView != null) {
            String[] oldLastView = lastView.split(",");
            for (String s : oldLastView) {
                if (!s.equals(book.getId())) {
                    newLastView.append(s).append(",");
                }
            }
        }
        //超过数量截取
        int LAST_VIEW_TOTAL = 3;
        if(newLastView.toString().split(",").length >= LAST_VIEW_TOTAL){
            newLastView.delete(0, newLastView.indexOf(",")+1);
        }
        newLastView.append(book.getId());
        cookie.setValue(newLastView.toString());
        response.addCookie(cookie);
    }
}
